package com.quickcode.example.concurrent;

import com.quickcode.annotation.Safe;
import lombok.Data;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟队列
 */
@Safe
public class DelayQueueExample {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<DealyObj> queue = new DelayQueue();

        DealyObj d1 = new DealyObj("zhangsan", 2);
        DealyObj d2 = new DealyObj("lisi", 5);
        DealyObj d3 = new DealyObj("wangwu", 3);

        queue.offer(d1);
        queue.offer(d2);
        queue.offer(d3);

        while (!queue.isEmpty()) {
            DealyObj value = queue.poll();
            if (value != null) {
                System.out.println(value.getName());
            }
        }

    }

    @Data
    static class DealyObj implements Delayed {

        private String name;

        private int delayTime;

        private long delay;

        public DealyObj(String name, int delayTime) {
            this.name = name;
            this.delayTime = delayTime;
            this.delay = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(delayTime, TimeUnit.SECONDS);
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return delay - System.currentTimeMillis();
        }

        @Override
        public int compareTo(Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }
    }
}